package risk.control.application.activity.base;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Window;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.io.BaseEncoding;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import risk.control.application.activity.IDCarScanActivity;
import risk.control.application.component.load.LoadDialog;
import risk.control.application.component.msg.ConfirmClickListener;
import risk.control.application.component.msg.ShowMsgDialog;
import risk.control.application.http.Api;
import risk.control.application.http.HttpPostClient;
import risk.control.application.http.SessionHelp;
import risk.control.application.http.callback.HttpCallback;
import risk.control.application.http.callback.UiCallback;
import risk.control.application.utils.data.ActivityMapUtils;
import risk.control.application.utils.ImageCompressor;
import risk.control.application.utils.data.TempCacheUtils;
import risk.control.application.utils.data.TokenUtils;
import risk.control.application.utils.mmkv.MMKVUtils;
import risk.control.application.utils.RouteJump;
import risk.control.application.utils.TimeUtils;
import risk.control.application.utils.mmkv.MMKV_KEY;


public abstract class BaseActivity extends AppCompatActivity {

    private LoadDialog mLoadDialog;
    private final List<String> requetIdList = new ArrayList<>();


    // 声明ActivityResultLauncher
    private ActivityResultLauncher<Intent> someActivityResultLauncher;

    //子类具体实现
    protected abstract void postData(HashMap<String, String> dataMap);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //禁止屏幕旋转
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
        //设置状态栏默认颜色
        Window window = getWindow();
        window.setStatusBarColor(Color.parseColor("#1677ff"));
        //添加进集合
        ActivityMapUtils.addActivity(this);
        //注册ActivityResult
        someActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == IDCarScanActivity.TAKE_PIC_OK_CODE) {
                Intent data = result.getData();
                if (data != null) {
                    String returnedData = data.getStringExtra("key");
                    //收到了拍照成功的回调->基类处理
                    handlePic();
                }
            }
        });
    }

    //打开身份证扫描页
    protected void startIDCarScanActivity() {
        Intent intent = new Intent(this, IDCarScanActivity.class);
        if (someActivityResultLauncher != null) {
            someActivityResultLauncher.launch(intent);
        }
    }

    //处理照片
    private void handlePic() {
        //测试-查看图片，可在手机目录查看图片，/路径在android/data/包名/..
        //FileUtils.saveByteArrayToExternalCache(InfoEntryActivity.this, photoData, "photoData.jpg");
        showLoadDialog("正在识别中...");
        //1、拿到照片数据
        byte[] originalImageData = (byte[]) TempCacheUtils.getInstance().get(TempCacheUtils.ID_CAR_PIC_CACHE_KEY);
        //2、压缩到100KB以内->异步(500K)图片质量越高识别率越高
        ImageCompressor.compressPic(originalImageData, 500 * 1024, Bitmap.CompressFormat.JPEG).subscribe(new SingleObserver<byte[]>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onSuccess(byte[] bytes) {
                //3、转为base64
                //String imgStr = Base64Util.encode(bytes);
                // 编码
                String imgStr = BaseEncoding.base64().encode(bytes);
                //请求接口-返回数据
                //自己服务器
                HashMap<String, String> params = new HashMap<>();
                params.put("IdCarBase4", imgStr);
                params.put("token", TokenUtils.get());//token参数
                getNetWordData(Api.OCR, params, new UiCallback() {
                    @Override
                    public void onSuccess(String respData) {
                        JSONObject jsonObject = (JSONObject) JSON.parse(respData);
                        JSONObject data = jsonObject.getJSONObject("data");
                        String userName = data.getString("userName");
                        String idNumber = data.getString("idNumber");
                        HashMap<String, String> dataMap = new HashMap<>();
                        dataMap.put("userName", userName);
                        dataMap.put("idNumber", idNumber);
                        postData(dataMap);//给子类实现
                        dismissLoadDialog();
                    }

                    @Override
                    public void onSpecialCode(String errorData) {
                        dismissLoadDialog();
                    }

                    @Override
                    public void onResolve() {
                        dismissLoadDialog();
                    }
                });
            }

            @Override
            public void onError(@NonNull Throwable e) {
                dismissLoadDialog();
                ShowMsgDialog msgDialog = new ShowMsgDialog(BaseActivity.this);
                msgDialog.showDialog(e.getMessage());
            }
        });

    }

    protected void showLoadDialog(String str) {
        if (mLoadDialog == null) {
            mLoadDialog = new LoadDialog(this);
        }
        mLoadDialog.showDialog(str);
    }

    protected void dismissLoadDialog() {
        if (mLoadDialog != null) {
            mLoadDialog.dismiss();
        }
    }

    protected void getNetWordData(String serviceName, HashMap<String, String> paramMap, UiCallback callBack) {
        //1、没超时就获取缓存的session数据
        String sessionData = MMKVUtils.getString(MMKV_KEY.KV_SESSION_ID_DATA);
        if (sessionData != null && !sessionData.isEmpty()) {
            //解析获取颁发时间
            JSONObject jsonObject = (JSONObject) JSON.parse(sessionData);
            JSONObject data = jsonObject.getJSONObject("data");
            String sessionId = data.getString("sessionId");//sessionId
            String issuanceTime = data.getString("issuanceTime");//session颁发时间
            long timestamp = System.currentTimeMillis();//当前时间
            //session有效期是15分钟，客户端与服务端可能存在时间误差，所以可提前几分钟刷新
            long timeDifference = TimeUtils.calculate(timestamp, Long.parseLong(issuanceTime));
            long limit = 1000 * 60 * 12;//session默认有效期15分钟
            if (Math.abs(timeDifference) < limit) {
                getData(this, serviceName, sessionId, paramMap, callBack);
                return;
            }
        }
        //2、超时或者为空状态->重新获取
        String requestId = HttpPostClient.getInstance().postData(this, Api.session, "", SessionHelp.getParams(), new HttpCallback() {
            @Override
            public void onSuccess(String respData) {
                //解析json
                JSONObject jsonObject = (JSONObject) JSON.parse(respData);
                //服务器返回的code->服务端必须保证结构完整
                String respCode = jsonObject.getString("code");
                String des = jsonObject.getString("des");
                if (respCode.equals("000")) {
                    //执行保存
                    JSONObject data = jsonObject.getJSONObject("data");
                    String sessionId = data.getString("sessionId");//session
                    MMKVUtils.putString(MMKV_KEY.KV_SESSION_ID_DATA, respData);
                    getData(BaseActivity.this, serviceName, sessionId, paramMap, callBack);
                } else {
                    ShowMsgDialog err = new ShowMsgDialog(BaseActivity.this);
                    err.showDialog(des);
                    callBack.onResolve();
                }
            }

            @Override
            public void onFailure(String errorData) {
                ShowMsgDialog err = new ShowMsgDialog(BaseActivity.this);
                err.showDialog(errorData);
                callBack.onResolve();
            }
        });
        requetIdList.add(requestId);
    }

    private void getData(Activity activity, String serviceName, String sessionId, HashMap<String, String> paramMap, UiCallback callBack) {
        String requestId = HttpPostClient.getInstance().postData(activity, serviceName, sessionId, paramMap, new HttpCallback() {
            @Override
            public void onSuccess(String respData) {
                /*
                 * 服务端响应成功
                 * 是json数据-》服务器异常返回
                 * 不是json-》正常返回加密数据
                 */
                JSONObject jsonObject = (JSONObject) JSON.parse(respData);
                //服务器返回的code->服务端必须保证结构完整
                String respCode = jsonObject.getString("code");
                String des = jsonObject.getString("des");
                switch (respCode) {
                    case "000":
                        //请求成功
                        callBack.onSuccess(respData);
                        break;

                    case "001":
                        //服务端错误提示
                        ShowMsgDialog msgDialog = new ShowMsgDialog(BaseActivity.this);
                        msgDialog.showDialog(des);
                        callBack.onResolve();
                        break;

                    case "011":
                        //session异常
                        ShowMsgDialog sessionErrorDialog = new ShowMsgDialog(BaseActivity.this);
                        sessionErrorDialog.showDialog(des);
                        sessionErrorDialog.setBtnClickListener(new ConfirmClickListener() {
                            @Override
                            public void onPositiveClick() {
                                //清空临时数据
                                //删除旧session
                                MMKVUtils.remove(MMKV_KEY.KV_SESSION_ID_DATA);
                                //退出app
                                ActivityMapUtils.finishAll();
                            }
                        });
                        callBack.onResolve();
                        break;

                    case "012":
                        //token异常
                        ShowMsgDialog tokenErrorDialog = new ShowMsgDialog(BaseActivity.this);
                        tokenErrorDialog.showDialog(des);
                        tokenErrorDialog.setBtnClickListener(new ConfirmClickListener() {
                            @Override
                            public void onPositiveClick() {
                                //关闭所有activity,清空用户数据-跳转登录页面
                                MMKVUtils.remove(MMKV_KEY.KV_USER_INFO_DATA);//token
                                TempCacheUtils.getInstance().clearAll();
                                HttpPostClient.getInstance().cancelAll();
                                ActivityMapUtils.finishAll();
                                RouteJump.start(BaseActivity.this, RouteJump.LOGIN_ACTION, null, true, true);
                            }
                        });
                        callBack.onResolve();
                        break;

                    case "014":
                        //服务端全局异常
                        ShowMsgDialog err = new ShowMsgDialog(BaseActivity.this);
                        err.showDialog(des);
                        callBack.onResolve();
                        break;

                    default:
                        //自行处理其他特殊状态码
                        callBack.onSpecialCode(respData);
                        break;
                }
            }

            @Override
            public void onFailure(String errorData) {
                ShowMsgDialog msgDialog = new ShowMsgDialog(BaseActivity.this);
                msgDialog.showDialog(errorData);
                if (!isDestroyed()) {
                    callBack.onResolve();
                }
            }
        });
        requetIdList.add(requestId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清空当前activity
        ActivityMapUtils.removeActivity(this);
        //清空所有call
        int size = requetIdList.size();
        if (!requetIdList.isEmpty()) {
            for (int i = 0; i < size; i++) {
                String tag = requetIdList.get(i);
                HttpPostClient.getInstance().cancel(tag);
            }
        }

    }

}
